import RenameModal from '@/components/rename-modal';
import {
  Avatar,
  Button,
  Card,
  Divider,
  Flex,
  Space,
  Spin,
  Tag,
  Typography,
} from 'antd';
import classNames from 'classnames';
import ChatConfigurationModal from './chat-configuration-modal';
import ChatContainer from './chat-container';
import {
  useClickConversationCard,
  useClickDialogCard,
  useEditDialog,
  useFetchConversationListOnMount,
  useFetchDialogOnMount,
  useGetChatSearchParams,
  useHandleItemHover,
  useRenameConversation,
  useSelectConversationListLoading,
  useSelectDerivedConversationList,
  useSelectDialogListLoading,
  useSelectFirstDialogOnMount,
} from './hooks';

import ChatOverviewModal from '@/components/api-service/chat-overview-modal';
import { useSetModalState, useTranslate } from '@/hooks/common-hooks';
import { useSetSelectedRecord } from '@/hooks/logic-hooks';
import { IDialog } from '@/interfaces/database/chat';
import { useState } from 'react';
import styles from './index.less';

const { Text } = Typography;

const Chat: React.FC = () => {
  const dialogList = useSelectFirstDialogOnMount();
  const { handleClickDialog } = useClickDialogCard();
  const { handleClickConversation } = useClickConversationCard();
  const { dialogId, conversationId } = useGetChatSearchParams();
  const { list: conversationList } = useSelectDerivedConversationList();
  const { activated, handleItemEnter, handleItemLeave } = useHandleItemHover();
  const {
    activated: conversationActivated,
    handleItemEnter: handleConversationItemEnter,
    handleItemLeave: handleConversationItemLeave,
  } = useHandleItemHover();
  const {
    conversationRenameLoading,
    initialConversationName,
    onConversationRenameOk,
    conversationRenameVisible,
    hideConversationRenameModal,
  } = useRenameConversation();
  const {
    dialogSettingLoading,
    initialDialog,
    onDialogEditOk,
    dialogEditVisible,
    clearDialog,
    hideDialogEditModal,
    showDialogEditModal,
  } = useEditDialog();
  const dialogLoading = useSelectDialogListLoading();
  const conversationLoading = useSelectConversationListLoading();
  const { t } = useTranslate('chat');
  const {
    visible: overviewVisible,
    hideModal: hideOverviewModal,
    showModal: showOverviewModal,
  } = useSetModalState();
  const { currentRecord, setRecord } = useSetSelectedRecord<IDialog>();

  const [expandedGroups, setExpandedGroups] = useState<{
    [nickname: string]: boolean;
  }>({});

  useFetchDialogOnMount(dialogId, true);

  const handleAppCardEnter = (id: string) => () => {
    handleItemEnter(id);
  };

  const handleConversationCardEnter = (id: string) => () => {
    handleConversationItemEnter(id);
  };

  const handleDialogCardClick = (dialogId: string) => () => {
    handleClickDialog(dialogId);
  };

  const handleConversationCardClick = (dialogId: string) => () => {
    handleClickConversation(dialogId);
  };

  useFetchConversationListOnMount();

  const handleGroupClick = (nickname: string) => {
    setExpandedGroups((prevState) => ({
      ...prevState,
      [nickname]: !prevState[nickname],
    }));
  };

  // Group dialogList by nickname
  const groupedDialogList = dialogList.reduce<{
    [nickname: string]: IDialog[];
  }>((acc, dialog) => {
    const groupNickname = dialog.nickname; // Using nickname for grouping
    if (!acc[groupNickname]) {
      acc[groupNickname] = [];
    }
    acc[groupNickname].push(dialog);
    return acc;
  }, {});

  return (
    <Flex className={styles.chatWrapper}>
      <Flex className={styles.chatAppWrapper}>
        <Flex flex={1} vertical>
          <Button type="primary">{t('allAssistant')}</Button>
          <Divider></Divider>
          <Flex className={styles.chatAppContent} vertical gap={10}>
            <Spin spinning={dialogLoading} wrapperClassName={styles.chatSpin}>
              {Object.keys(groupedDialogList).map((nickname) => (
                <div key={nickname}>
                  <div
                    onClick={() => handleGroupClick(nickname)}
                    style={{
                      backgroundColor: '#fafafa',
                      border: '1px solid #e6e6e6',
                      width: '260px',
                      height: '60px',
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      padding: '0 16px',
                      cursor: 'pointer',
                      boxShadow: expandedGroups[nickname]
                        ? '0 4px 12px rgba(0, 0, 0, 0.1)'
                        : 'none',
                    }}
                  >
                    <Text style={{ fontSize: '16px', fontWeight: '500' }}>
                      {nickname}
                    </Text>
                    <span>{expandedGroups[nickname] ? '▲' : '▼'}</span>
                  </div>
                  {expandedGroups[nickname] &&
                    groupedDialogList[nickname].map((x) => (
                      <Card
                        key={x.id}
                        hoverable
                        className={classNames(styles.chatAppCard, {
                          [styles.chatAppCardSelected]: dialogId === x.id,
                        })}
                        onMouseEnter={handleAppCardEnter(x.id)}
                        onMouseLeave={handleItemLeave}
                        onClick={handleDialogCardClick(x.id)}
                        style={{
                          marginLeft: '20px',
                          marginBottom: '8px', // 垂直间距
                          borderRadius: '10px', // 圆角更大
                          backgroundColor: '#ffffff',
                          border: '1px solid #e6e6e6',
                          padding: '10px 18px', // 左右空间稍大
                          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
                        }}
                      >
                        <Flex justify="space-between" align="center">
                          <Space size={15}>
                            <Avatar src={x.icon} shape={'square'} />
                            <section>
                              <b>
                                <Text
                                  ellipsis={{ tooltip: x.name }}
                                  style={{
                                    width: 130,
                                    fontSize: '14px',
                                    fontWeight: '400',
                                  }}
                                >
                                  {x.name}
                                </Text>
                              </b>
                              <div
                                style={{ color: '#888888', fontSize: '12px' }}
                              >
                                {x.description}
                              </div>
                              <div
                                style={{ color: '#555555', fontSize: '12px' }}
                              >
                                {t('nickname')}:{x.nickname}
                              </div>
                            </section>
                          </Space>
                        </Flex>
                      </Card>
                    ))}
                </div>
              ))}
            </Spin>
          </Flex>
        </Flex>
      </Flex>
      <Divider type={'vertical'} className={styles.divider}></Divider>
      <Flex className={styles.chatTitleWrapper}>
        <Flex flex={1} vertical>
          <Flex
            justify={'space-between'}
            align="center"
            className={styles.chatTitle}
          >
            <Space>
              <b>{t('chat')}</b>
              <Tag>{conversationList.length}</Tag>
            </Space>
          </Flex>
          <Divider></Divider>
          <Flex vertical gap={10} className={styles.chatTitleContent}>
            <Spin
              spinning={conversationLoading}
              wrapperClassName={styles.chatSpin}
            >
              {conversationList.map((x) => (
                <Card
                  key={x.id}
                  hoverable
                  onClick={handleConversationCardClick(x.id)}
                  onMouseEnter={handleConversationCardEnter(x.id)}
                  onMouseLeave={handleConversationItemLeave}
                  className={classNames(styles.chatTitleCard, {
                    [styles.chatTitleCardSelected]: x.id === conversationId,
                  })}
                >
                  <Flex justify="space-between" align="center">
                    <div>
                      <Text
                        ellipsis={{ tooltip: x.name }}
                        style={{ width: 150 }}
                      >
                        {x.name}
                      </Text>
                    </div>
                  </Flex>
                </Card>
              ))}
            </Spin>
          </Flex>
        </Flex>
      </Flex>
      <Divider type={'vertical'} className={styles.divider}></Divider>
      <ChatContainer></ChatContainer>
      {dialogEditVisible && (
        <ChatConfigurationModal
          visible={dialogEditVisible}
          initialDialog={initialDialog}
          showModal={showDialogEditModal}
          hideModal={hideDialogEditModal}
          loading={dialogSettingLoading}
          onOk={onDialogEditOk}
          onCancel={hideDialogEditModal}
        ></ChatConfigurationModal>
      )}
      {conversationRenameVisible && (
        <RenameModal
          visible={conversationRenameVisible}
          name={initialConversationName}
          loading={conversationRenameLoading}
          onOk={onConversationRenameOk}
          onCancel={hideConversationRenameModal}
        ></RenameModal>
      )}
      {overviewVisible && (
        <ChatOverviewModal
          visible={overviewVisible}
          currentRecord={currentRecord}
          onCancel={hideOverviewModal}
          setRecord={setRecord}
        ></ChatOverviewModal>
      )}
    </Flex>
  );
};

export default Chat;
